package com.satan.fmmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.satan.fmmall.entity.UserAddr;
import com.satan.fmmall.mapper.UserAddrMapper;
import com.satan.fmmall.service.UserAddrService;
import com.satan.fmmall.vo.ResCode;
import com.satan.fmmall.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @ClassName UserAddrServiceImpl
 * @Description TODO
 * @date 2022/4/15 20:02
 * @Version 1.0
 */
@Service
public class UserAddrServiceImpl implements UserAddrService {
    @Resource
    private UserAddrMapper userAddrMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo listAddrsByUserId(Integer UserId) {
        LambdaQueryWrapper<UserAddr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAddr::getUserId, UserId);
        queryWrapper.eq(UserAddr::getStatus, 1);
        queryWrapper.orderByDesc(UserAddr::getCommonAddr);
        return ResultVo.success(userAddrMapper.selectList(queryWrapper));
    }

    @Override
    public ResultVo deleteAddrByAddrId(String addrId) {
        int i = userAddrMapper.deleteById(addrId);
        if (i > 0) {
            return ResultVo.success(null);
        }else {
           return ResultVo.fail(ResCode.DELETE_ERROR);
        }
    }

    @Override
    public ResultVo updateAddrByEntity(UserAddr userAddr) {
        int i;
        if(userAddr.getCommonAddr()==1){
            UserAddr userAddr1=new UserAddr();
            userAddr1.setCommonAddr(0);
            LambdaUpdateWrapper<UserAddr> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserAddr::getCommonAddr, 1);
            userAddrMapper.update(userAddr1,updateWrapper);
        }
        if (StringUtils.isEmpty(userAddr.getAddrId())) {
            userAddr.setAddrId(null);
            System.out.println("新增");
            i=userAddrMapper.insert(userAddr);
        }else {
            System.out.println("修改");
            LambdaUpdateWrapper<UserAddr> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserAddr::getAddrId, userAddr.getAddrId());
            i = userAddrMapper.update(userAddr,updateWrapper);
        }

        if (i>0){
            return ResultVo.success(null);
        }else {
            return ResultVo.fail(ResCode.UPDATE_ERROR);
        }
    }
}
